package org.git.movie.filters;


import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig;
import org.apache.commons.lang3.StringUtils;
import org.git.movie.helper.UrlBlockHandlerHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

//@WebFilter(urlPatterns = "/*", filterName = "traceIdFilter")
public class TraceIdFilter implements Filter {
    public static final String TRACE_KEY = "traceId";
    private static final Logger logger = LoggerFactory.getLogger(TraceIdFilter.class);



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        参考wiki: https://github.com/alibaba/Sentinel/wiki/%E4%B8%BB%E6%B5%81%E6%A1%86%E6%9E%B6%E7%9A%84%E9%80%82%E9%85%8D#spring-cloud
        WebCallbackManager.setUrlBlockHandler(new UrlBlockHandlerHelper());
//        WebServletConfig.setBlockPage("/sentinel/blockPage");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {



        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //先从param里取，没有的话从header里取，还没有的话再创建
        String traceId = request.getParameter("TRACE_ID");
        if (StringUtils.isBlank(traceId)){
            traceId = httpServletRequest.getHeader("X-Request-Id");
        }

        if (StringUtils.isBlank(traceId)){
            traceId = UUID.randomUUID().toString().replace("-", "");
//            logger.debug("生成traceId:{}", traceId);
        }

        MDC.put( TRACE_KEY, traceId);

        try{
            chain.doFilter(request, response);

        }catch (Exception e){

            throw  e;
        }finally {
            MDC.remove(TRACE_KEY);
        }




    }

    @Override
    public void destroy() {

    }
}